/*=====================================================================================
   Program Name: avVTR
   This is a program that averages VTR coefficients using the Group variable. 
   
Program written by Won-ho Park, University of Michigan
Copyright Won-ho Park, Aug. 2003
=======================================================================================
========================================================================================*/

program define avVTR, rclass sortpreserve
	version 7.0
	syntax varlist(min=2 numeric) [if] [in] , SECond(varlist numeric min=2) Group(varname) [ecol(passthru) TOLerance(passthru) Format(passthru)]
	marksample touse, strok
tempname nofgroups
qui tab `group'
local categ = r(r)

qui VTR `varlist', sec(`second')
	sca nofp_t2 = rowsof(r(Pops))
	sca nofp_t1 = colsof(r(Pops))
	mat prelimmat = r(Out)
*	mat list prelimmat, t("Voter Transition Matrix, All Sample")
	sca totalvotes = prelimmat[nofp_t2+1, nofp_t1+1]
	mat vote_t1 = prelimmat[nofp_t2+1, 1..nofp_t1]
	mat vote_t2 = prelimmat[1..nofp_t2, nofp_t1+1]
	mat nonw_Pops = r(Pops)

mat Pops = J(nofp_t2, nofp_t1, 0)
qui tab `group'
local `nofgroups'=r(r)
di as txt "There are ``nofgroups'' number of groups"
qui tabstat `group', by(`group') save

forvalues i=1/``nofgroups''{
		local group`i' `r(name`i')'
*		di `group`i''
}

*qui vallist `group'
*tokenize `r(list)'
*local `categ' `r(list)

di as res "Now going through all the groups..." _c
forvalues i=1/``nofgroups''{
*	VTR `varlist' if `group'==`r(name`i')', sec(`second')
*	capture qui VTR `varlist' if `group'==`r(name`i')', sec(`second')
	capture qui VTR `varlist' if `group'==`group`i'', sec(`second')
	if _rc==2000{
		di as err "No obs. in Group `group`i'' " _c
	}
*	mat list r(n)
	capture mat Pops = Pops + r(Pops)
	if _rc~=0{
		di as err "A problem Occurred in Group `group`i'' "  _c
	}
	di as text "." _c
}
/* The way this program works, is to just add up number of predicted population in each cell*/


local nofp_t1 = nofp_t1
local nofp_t2 = nofp_t2
*mat list Pops
mat V1s = J(1,nofp_t1, 0)
*mat list V1s
forvalues i=1(1)`nofp_t2'{
	mat V1s = V1s + Pops[`i', 1...]
}

mat vtr = Pops[1...,1]/V1s[1,1]
foreach j of numlist 2/`nofp_t1'{
	mat next = Pops[1...,`j']/V1s[1,`j']
	mat vtr=vtr,next
}

mat colname  vtr = `varlist'
mat rownames vtr = `second'
mat list vtr, t("Voter Transition Matrix, Averaged across ``nofgroups'' Groups in `group'")
return mat vtr vtr
mat uncond = Pops/totalvotes
mat list uncond, t("Unconditional Voter Transition Matrix")

end
